package com.smartwebx.fr.controller.editor;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.MoreObjects;
import com.google.common.base.Predicate;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.smartwebx.fr.bean.SimpleUseArgConf;
import com.smartwebx.fr.bean.SiteObj;
import com.smartwebx.fr.bean.mysql.PageUseArg;
import com.smartwebx.fr.service.ckeditor.UseArgConfService;
import com.smartwebx.fr.util.CurrLocalSeIdUseParam;
import com.smartwebx.fr.util.EditorConfProperties;
import com.smartwebx.fr.util.InitLoadingSites;

@Controller
@RequestMapping("/editor/useArgList")
public class UseArgListController {
	Logger logger4J = Logger.getLogger(UseArgListController.class);

	@Autowired
	private UseArgConfService useArgConfService;

	private ObjectMapper mapper = new ObjectMapper();

	@RequestMapping
	public Map<String, Object> getIndex(Integer pageId) {
		Map<String, Object> root = new HashMap<String, Object>();

		try {
			root.put("uaList", useArgConfService.getListByPageId(pageId));
		} catch (Exception e) {
			logger4J.error(e);
		}

		Map<String, String> USE_CONF_TYPE = EditorConfProperties.USE_CONF_TYPE;
		Map<String, String> DL_EXT_CONF = EditorConfProperties.DL_EXT_CONF;

		// 放置用户参数类型键值对
		root.put("useConfType", USE_CONF_TYPE);
		// 放置用户扩展参数类型键值对
		root.put("dlExtConf", DL_EXT_CONF);

		return root;
	}

	@RequestMapping(value = "/getParamByPageId")
	@ResponseBody
	public Object getParamByPageId(Integer pageId) {
		List<PageUseArg> params = useArgConfService.getListByPageId(pageId);
		return params;
	}

	@RequestMapping(value = "/saveArgsCache")
	@ResponseBody
	public void saveArgsCache(String sessionId, String argJsons) throws Exception {
		List<PageUseArg> cacheArgs = mapper.readValue(argJsons, new TypeReference<List<PageUseArg>>() {
		});
		// 缓存参数
		CurrLocalSeIdUseParam.putUseParams(sessionId, cacheArgs);
	}

	@RequestMapping(value = "/getSimpleParamByPageId")
	@ResponseBody
	public Object getSimpleParamByPageId(Integer pageId) throws Exception {
		List<SimpleUseArgConf> params = useArgConfService.getSimpleUseArgConfs(pageId);
		return params;
	}

	@RequestMapping(value = "/saveUseArgData")
	@ResponseBody
	public Map<String, Object> saveUserArgData(String data) throws IOException {
		String id = useArgConfService.saveOrUpdate(data);
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("result", "success");
		result.put("id", id);
		return result;
	}

	@RequestMapping(value = "/saveParamShowValue")
	@ResponseBody
	public void saveParamShowValue(String sessionId, String objs, Integer pageId) throws IOException {
		ObjectMapper mapper = new ObjectMapper();
		List<PageUseArg> useArgConfs = mapper.readValue(objs, new TypeReference<List<PageUseArg>>() {
		});
//		Page page = pageDao.selectByPrimaryKey(pageId);
//		Boolean rememberCache = MoreObjects.firstNonNull(page.getRemberParam(), false);
		useArgConfService.updateShowValueById(sessionId, useArgConfs);
	}

	@RequestMapping(value = "/delUseArgData")
	public @ResponseBody String delDataSource(String uaId) {
		useArgConfService.deleteById(uaId);
		return "success";
	}

	/**
	 * 交换两个元素的顺序
	 * 
	 * @param data
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/swapOrder")
	public @ResponseBody String swapOrder(String data) throws IOException {
		useArgConfService.swapOrder(data);
		return "success";
	}

	@RequestMapping(value = "/findSitesByIds")
	@ResponseBody
	public Object findSites(String ids) {
		Collection<SiteObj> sites = Lists.newArrayList();

		Map<String, String> allSites = InitLoadingSites.getAllSites();
		for (String id : StringUtils.split(ids, ',')) {
			String val = allSites.get(id);
			if (val != null) {
				SiteObj obj = new SiteObj(id, val + '[' + id + ']');
				sites.add(obj);
			}
		}

		return ImmutableMap.of("items", sites);
	}

	@RequestMapping(value = "/findSiteNamesByIds")
	@ResponseBody
	public String findSiteNameById(String ids) {
		return useArgConfService.findSiteNameById(ids);
	}

	@RequestMapping(value = "/findSingleSite")
	public @ResponseBody Object findSingleSite(final String key, String filterIds) {
		final List<String> filterIdList = Splitter.on(',').splitToList(MoreObjects.firstNonNull(filterIds, ""));

		Map<String, String> findMaps = Maps.filterEntries(InitLoadingSites.getAllSites(),
				new Predicate<Entry<String, String>>() {
					@Override
					public boolean apply(Entry<String, String> input) {
						String id = input.getKey();
						String val = input.getValue();
						// 排除需要过滤的站码
						if (filterIdList.contains(id)) {
							return false;
						} else {
							String text = (val + id);
							return StringUtils.indexOf(text, key) >= 0;
						}
					}
				});

		return ImmutableMap.of("items", converMapToList(findMaps));
	}

	private List<SiteObj> converMapToList(Map<String, String> converMap) {
		List<SiteObj> result = Lists.newArrayList();

		for (String key : converMap.keySet()) {
			String val = converMap.get(key);
			SiteObj obj = new SiteObj(key, val + '[' + key + ']');
			result.add(obj);
		}
		return result;
	}
}
